<template>
  <div class="p-2">
    <!-- <el-form
      :model="queryData"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="区域名称" prop="name">
        <el-input
          v-model="queryData.region"
          placeholder="请输入区域名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form> -->

    <el-card shadow="never">
      <!-- 按钮区 -->
      <template #header>
        <el-row :gutter="10" class="mb-1">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="Plus"
              @click="addRoot()"
              v-hasPermi="['system:permission:add']"
            >
              新增根节点
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="DocumentAdd"
              @click="handleSaveRegion()"
              v-hasPermi="['system:permission:add']"
            >
              保存
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              plain
              icon="Refresh"
              @click="handleReset()"
              v-hasPermi="['system:permission:add']"
            >
              重置
            </el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple"
              @click="addRoot()"
              v-hasPermi="['system:permission:add']"
            >
              删除
            </el-button>
          </el-col> -->
          <right-toolbar
            v-model:showSearch="showSearch"
            @queryTable="getRegionTree"
            :search="false"
          ></right-toolbar>
        </el-row>
      </template>

      <div style="width: 30vw">
        <el-tree
          v-loading="loading"
          :data="defaultRegionTree"
          node-key="id"
          :default-expand-all="false"
          show-checkbox
          :expand-on-click-node="false"
          :default-checked-keys="childRegionIds"
          @check="nodeSelection"
        >
          <template #default="{ node, data }">
            <span class="custom-tree-node">
              <span>{{ node.label }}</span>
              <span class="setting">
                <span v-hasPermi="['system:region:add']"
                      v-if="data.level !== 4"
                >
                  <el-tooltip
                    content="新增"
                    placement="top"
                    :enterable="false"
                    :hide-after="0"
                    :offset="2"
                  >
                    <el-button
                      link
                      type="primary"
                      icon="Plus"
                      @click="handleRegionAdd(data)"
                    ></el-button>
                  </el-tooltip>
                </span>
                <span v-hasPermi="['system:region:edit']" class="pl-10px">
                  <el-tooltip
                    content="编辑"
                    placement="top"
                    :enterable="false"
                    :hide-after="0"
                    :offset="2"
                  >
                    <el-button
                      link
                      type="primary"
                      icon="Edit"
                      @click="handleRegionEdit(data)"
                    ></el-button>
                  </el-tooltip>
                </span>
                <span v-hasPermi="['system:region:remove']"  class="pl-10px">
                  <el-tooltip
                    content="删除"
                    placement="top"
                    :enterable="false"
                    :hide-after="0"
                    :offset="2"
                  >
                    <el-button
                      link
                      type="primary"
                      icon="Delete"
                      @click="handleDelete(data)"
                    ></el-button>
                  </el-tooltip>
                </span>
              </span>
            </span>
          </template>
        </el-tree>
      </div>
    </el-card>

    <!-- 新增根节点 -->
    <el-dialog
      :title="dialogStatus.title"
      v-model="dialogStatus.isAddRoot"
      width="450px"
      append-to-body
      center
      draggable
      @close="closeDialog"
    >
      <el-form
        ref="dialogFormRef"
        :model="regionBO"
        :rules="rootRegionRules"
        label-width="120px"
      >
        <!-- <el-form-item label="所属区域" prop="regionName">
          <el-input
            v-model="regionBO.regionName"
            placeholder="请输入区域名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item> -->

        <el-form-item label="区域名称" prop="regionName">
          <el-input
            v-model="regionBO.regionName"
            placeholder="请输入区域名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="虚拟行政编码" prop="virtualCode">
          <el-input
            v-model="regionBO.virtualCode"
            placeholder="请输入虚拟行政编码"
            clearable
          />
        </el-form-item>
        <el-form-item label="区域编码" prop="regionCode">
          <el-input
            v-model="regionBO.regionCode"
            placeholder="请输入区域编码"
            clearable
          />
        </el-form-item>

        <el-form-item label="区域级别" prop="level">
          <el-select v-model="regionBO.level" clearable placeholder="请选择">
            <el-option
              v-for="item in selectArr.levelArr"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" icon="Check" @click="submit">
            确定
          </el-button>
          <el-button icon="Close" @click="dialogStatus.isAddRoot = false">
            关闭
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 新增子节点 -->
    <el-dialog
      :title="dialogStatus.title"
      v-model="dialogStatus.isAddNode"
      width="450px"
      append-to-body
      center
      draggable
      @close="closeDialog"
    >
      <el-form
        ref="dialogFormRef"
        :model="regionBO"
        :rules="subRegionRules"
        label-width="120px"
      >
        <!-- <el-form-item label="区域全称" prop="parentName" v-show="isRoot">
        <el-input
          disabled
          v-model="regionBO.mergerName"
          placeholder="请输入区域全称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
        <el-form-item label="所属区域" prop="owningRegion">
          <el-input
            disabled
            v-model="regionBO.owningRegion"
            placeholder="请输入区域名称"
            clearable
          />
        </el-form-item>

        <el-form-item label="区域名称" prop="regionName">
          <el-input
            v-model="regionBO.regionName"
            placeholder="请输入区域名称"
            clearable
          />
        </el-form-item>
<!--        <el-form-item label="虚拟行政编码" prop="virtualCode">-->
<!--          <el-input-->
<!--            v-model="regionBO.virtualCode"-->
<!--            placeholder="请输入虚拟行政编码"-->
<!--            clearable-->
<!--          />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="区域编码" prop="name">-->
<!--          <el-input-->
<!--            v-model="regionBO.regionCode"-->
<!--            placeholder="请输入区域编码"-->
<!--            clearable-->
<!--          />-->
<!--        </el-form-item>-->

        <el-form-item label="区域级别">
          <el-select v-model="regionBO.level" clearable placeholder="请选择">
            <el-option
              v-for="item in selectArr.levelArr"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" icon="Check" @click="submit">
            确定
          </el-button>
          <el-button icon="Close" @click="dialogStatus.isAddNode = false">
            关闭
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {
  getDefaultRegionTree as getDefaultRegionTreeApi,
  addRegion as regionAddApi,
  getRegionDetail as getRegionDetailApi,
  updateRegion as regionEditApi,
  deleteRegion as regionDeleteApi,
  saveRegionSelection as saveRegionApi,
} from "@/service/api/system/region";
import { ElForm } from "element-plus";
import {
  RegionNode,
  RegionSelectionVo,
  SysRegionBO,
  SysRegionVo,
} from "@/service/api/system/region/types";
import to from "await-to-js";
import RightToolbar from "@/components/RightToolbar/index.vue";
import { BaseResponse } from "@/service/api/type.ts";

const showSearch = ref(true);
const dialogFormRef = ref(ElForm);
const loading = ref(false);
const initDialogStatus = {
  title: "",
  isAddNode: false,
  isAddRoot: false,
};
const initRegionBO: SysRegionBO = {
  // 区域编码
  regionCode: "",
  // 区域名称
  regionName: "",
  // 全称
  mergerName: "",
  id: "",
  // 级别
  level: undefined,
  // 虚拟编码
  virtualCode: "",
  owningRegion: "",
  parentId: "",
};
const selectArr = {
  levelArr: [
    {
      label: "省级",
      value: 2,
    },
    {
      label: "市级",
      value: 3,
    },
    {
      label: "区级",
      value: 4,
    },
  ],
};

const data = reactive({
  // queryData: {
  //   region: "",
  // },
  regionBO: { ...initRegionBO },
  dialogStatus: { ...initDialogStatus },
  defaultRegionTree: <RegionNode[]>[],
  rootRegionRules: {
    regionName: [
      { required: true, message: "地区名称不能为空", trigger: "blur" },
    ],
    regionCode: [
      { required: true, message: "区域编码不能为空", trigger: "blur" },
    ],
    virtualCode: [
      { required: true, message: "虚拟行政编码不能为空", trigger: "blur" },
    ],
    // level: [{ required: true, message: "级别不能为空", trigger: "blur" }],
  },
  subRegionRules: {
    regionName: [
      { required: true, message: "地区名称不能为空", trigger: "blur" },
    ],
  },

});

const { defaultRegionTree, dialogStatus, regionBO, rootRegionRules, subRegionRules } = toRefs(data);

/**
 * 新增子节点
 * @param row
 */
const handleRegionAdd = async (row: any) => {
  console.log(row);
  const [err, res] = await to<BaseResponse<SysRegionVo>, any>(
    getRegionDetailApi(row.id),
  );
  if (!err) {
    // 获取所属区域
    console.log(res);
    regionBO.value.owningRegion = res?.data?.mergerName;
    // 获取父id
    regionBO.value.parentId = row.id;
    regionBO.value.level = row.level + 1;
    dialogStatus.value.isAddNode = true;
    dialogStatus.value.title = "新增子节点";
  }
};

/**
 * 编辑节点
 * @param row
 */
const handleRegionEdit = async (row: SysRegionVo) => {
  console.log(row);
  const [err, res] = await to<BaseResponse<SysRegionVo>, any>(
    getRegionDetailApi(row.id ?? ""),
  );
  if (!err) {
    regionBO.value = (res?.data !== null) ? {...res?.data} : initRegionBO;
    // 根据全称获取所属名称
    let currentMergerName = "";
    const parts = res?.data?.mergerName?.split(" ") ?? [];
    if (parts.length > 0) {
      const lastPartIndex = parts.length - 1;
      currentMergerName = parts.slice(0, lastPartIndex).join(" ");
    }
    regionBO.value.owningRegion = currentMergerName;
    console.log(res, currentMergerName);
    dialogStatus.value.title = "编辑节点";
    dialogStatus.value.isAddNode = true;
  }
};

// 所有已勾选的id
const allRegionIds = ref<string[]>([]);
// 所有已勾选的子节点id
const childRegionIds = ref<string[]>([]);

/**
 * 获取全部地区列表
 */
const getRegionTree = async (): Promise<boolean> => {
  loading.value = true;
  const [err, res] = await to<BaseResponse<RegionSelectionVo>, any>(
    getDefaultRegionTreeApi(),
  );

  if (!err) {
    childRegionIds.value = res?.data?.checkedSonIds ?? [];
    allRegionIds.value = res?.data?.checkedIds ?? [];
    defaultRegionTree.value = res?.data?.tree ?? [];
    // 默认为后台已勾选的设置ischecked
    setDefaultChecked(defaultRegionTree.value);
    console.log(res?.data);

    loading.value = false;
    return true;
  }

  loading.value = false;
  return false;
};

/**
 * 新增根节点
 */
const addRoot = () => {
  dialogStatus.value.isAddRoot = true;
  dialogStatus.value.title = "新增根节点";
  regionBO.value.level = 2;
};

/**
 * 初次渲染设置选中状态
 * @param treeArr
 */
const setDefaultChecked = (treeArr: any) => {
  for (let i = 0; i < treeArr.length; i++) {
    let node = treeArr[i];
    // 遍历每个节点并且设置为已勾选
    node.isChecked = allRegionIds.value.some((item) => item === node.id);
    if (node.children && node.children.length > 0) {
      setDefaultChecked(node.children);
    }
  }
};

/**
 * 遍历permissionTree,设置已勾选的为true
 * @param treeArr
 */
const setDynamicChecked = (treeArr: any) => {
  for (let i = 0; i < treeArr.length; i++) {
    const node = treeArr[i];
    // 找到已勾选列表是否有
    // 有就勾上 没有就不勾
    node.isChecked = checkedNodes.value.some((item: any) => {
      return item.id === node.id;
    });
    if (node.children && node.children.length > 0) {
      setDynamicChecked(node.children); // 递归调用，处理每个子节点
    }
  }
};

/**
 * 已勾选的节点(包括半勾)
 */
const checkedNodes = ref();
/**
 * 节点被勾选
 * @param node
 * @param status
 */
const nodeSelection = (node: any, status: any) => {
  // 保存已勾选的节点
  console.log(node);

  checkedNodes.value = [
    ...JSON.parse(JSON.stringify(status.checkedNodes)),
    ...JSON.parse(JSON.stringify(status.halfCheckedNodes)),
  ];
  console.log(defaultRegionTree.value, checkedNodes.value);
  // 为所有数据的设置ischecked
  setDynamicChecked(defaultRegionTree.value);
};

/**
 * 保存最终所有勾选状态的节点id
 */
const finalNodesIds: any = ref([]);

/**
 * 遍历拿到树形节点中所有选中的节点
 * @param treeArr
 */
const getCheckedNodes = (treeArr: any) => {
  for (let i = 0; i < treeArr.length; i++) {
    let node = treeArr[i];
    if (node.isChecked) {
      console.log(node);
      finalNodesIds.value.push(node.id);
    } else {
      node.isChecked = false;
    }
    if (node.children && node.children.length > 0) {
      getCheckedNodes(node.children); // 递归调用，处理每个子节点
    }
  }
};

/**
 * 保存已勾选按钮
 */
const handleSaveRegion = async () => {
  const [err, confirm] = await to<string, string>(
    ElMessageBox.confirm("是否确定要保存所有已勾选的地区?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }),
  );
  if (err === "cancel") {
    ElMessage({
      type: "info",
      message: "取消保存",
    });
  } else if (confirm === "confirm") {
    // 拿到所有已勾选id
    getCheckedNodes(defaultRegionTree.value);
    console.log(finalNodesIds.value);
    const [err, res] = await to<BaseResponse<any>, any>(
      saveRegionApi(finalNodesIds.value),
    );
    if (!err) {
      console.log(res);
      // 保存成功后清空finalNodesIds
      finalNodesIds.value = [];
      ElMessage({
        type: "success",
        message: "保存成功",
      });
      getRegionTree();
    }
  }
};

/**
 * 取消按钮
 */
const handleReset = async () => {
  const [err, confirm] = await to<string, string>(
    ElMessageBox.confirm("是否重置当前所有操作，恢复上次加载状态?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }),
  );
  if (err === "cancel") {
    ElMessage({
      type: "info",
      message: "取消重置",
    });
  } else if (confirm === "confirm") {
    const response = await getRegionTree();
    if (response) {
      ElMessage({
        type: "success",
        message: "重置成功",
      });
    }
  }
};

/**
 * 关闭dialog
 */
const closeDialog = () => {
  dialogStatus.value = Object.assign({}, initDialogStatus);
  regionBO.value = Object.assign({}, initRegionBO);
};

/**
 * dialog提交按钮
 */
const submit = async () => {
  dialogFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      // 验证通过
      console.log(regionBO.value);
      loading.value = true;
      // 有id为编辑
      if (regionBO.value.id) {
        const [err, res] = await to<BaseResponse<any>, any>(
          regionEditApi(regionBO.value),
        );
        if (!err) {
          console.log(res);
          ElMessage({
            type: "success",
            message: "修改成功",
          });
          getRegionTree();
        }
        dialogStatus.value = Object.assign({}, initDialogStatus);
        loading.value = false;
      }
      // 无id为新增
      else {
        // 新增
        const [err, res] = await to<BaseResponse<any>, any>(
          regionAddApi(regionBO.value),
        );
        if (!err) {
          console.log(res);
          ElMessage({
            type: "success",
            message: "新增成功",
          });
          getRegionTree();
        }
        dialogStatus.value = Object.assign({}, initDialogStatus);
        loading.value = false;
      }
    }
  });
};

/**
 * 处理删除
 * @param row
 */
const handleDelete = async (row: any) => {
  console.log(row);
  loading.value = true;
  const [err, confirm] = await to<string, string>(
    ElMessageBox.confirm("是否确定要删除该节点?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }),
  );

  if (err === "cancel") {
    ElMessage({
      type: "success",
      message: "取消成功",
    });
  } else if (confirm === "confirm") {
    if (row.id) {
      const [err, res] = await to<BaseResponse<any>, any>(
        regionDeleteApi(row.id),
      );
      if (!err) {
        console.log(res);
        await getRegionTree();
        ElMessage({
          type: "success",
          message: "删除成功",
        });
      }
    }
  }
  loading.value = false;

  // else {
  //   const [err, res] = await to(regionDeleteApi(ids.value));
  //   if (!err) {
  //     console.log(res);
  //     ElMessage({
  //       type: "success",
  //       message: "删除成功",
  //     });
  //   } else {
  //     ElMessage({
  //       type: "error",
  //       message: "删除失败",
  //     });
  //   }
  // }
};

onMounted(() => {
  getRegionTree();
});
</script>

<style scoped lang="scss">
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
